package login;

import java.io.*; 
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class Authenticate
 */
@WebServlet("/Authenticate")
public class Authenticate extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Authenticate() {
        super();
        
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        

		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		PrintWriter out = response.getWriter();
		String username = request.getParameter("username"); 
		String password = request.getParameter("password"); 
		
		if (request.getParameter("submit").equals("Register")){
			response.sendRedirect("account.jsp"); 
		}
		else {
			int userType = 0; //0 for incorrect login, 1 for manager, 2 for customer. 
			try {
				LoginMachine lm = new LoginMachine();
				userType = lm.processLogin(username, password); 
				
				//incorrect login
				if (userType == 0){
					response.sendRedirect("login.jsp?status=failed"); 
				}
				//manager
				else if (userType == 1) {
					Cookie cookie = new Cookie("username", username);
					Cookie isManager = new Cookie("isManager", "true"); 
					response.addCookie(isManager); 
					response.addCookie(cookie); 
					response.sendRedirect("account.jsp?m"); 
				}
				//customer
				else {
					Cookie cookie = new Cookie("username", username);
					response.addCookie(cookie); 
					Cookie isManager = new Cookie("isManager", "false"); 
					response.addCookie(isManager); 
					response.sendRedirect("account.jsp"); 
					//response.sendRedirect("http://www.amazon.com"); 
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace(); 
				out.println("ClassNotFoundException"); 
			}
			catch (SQLException e){
				e.printStackTrace(); 
				out.println("SQLException"); 
			}
		}
	
	}

}
